/**   
* @Title: StopSignalReceiver.java
* @Package org.xaoyaoyao.spider.util
* @Description: TODO
* @author xaoyaoyao
* @date Jan 25, 2019 11:08:53 AM
* @version V1.0   
*/
package org.xaoyaoyao.spider.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * @ClassName: StopSignalReceiver
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 25, 2019 11:08:53 AM
 * 
 */
@Slf4j
@SuppressWarnings("restriction")
public class StopSignalReceiver implements SignalHandler {

	private static StopSignalReceiver stopSignalReceiver = null;

	private static boolean isReceived = false;

	private void signalCallback(Signal signal) {
		isReceived = true;
		log.info("signal:" + signal.getName() + " is recevied, program will close!");
	}

	public void handle(Signal signal) {
		signalCallback(signal);
	}

	/**
	 * 功能:判断是否收到信号.
	 * 
	 * @param 无
	 * @return true:收到信号, false:没有收到信号.
	 * @exception 无
	 */
	public static boolean isReceived() {
		if (stopSignalReceiver == null) {
			installStopSignals();
		}
		return isReceived;
	};

	/**
	 * 功能:安装停止信号
	 * 
	 * @param 无
	 * @return StopSignalHandler对象或者null.
	 * @exception 无
	 */
	private static StopSignalReceiver installStopSignals() {
		if (stopSignalReceiver == null) {
			stopSignalReceiver = new StopSignalReceiver();
			// 注册信号
			Signal sigTerm = new Signal("TERM");// 这是kill时默认发送的信号
			Signal sigInt = new Signal("INT");// 这是按下"ctrl+c"组合键时发送的信号
			Signal.handle(sigTerm, stopSignalReceiver);
			Signal.handle(sigInt, stopSignalReceiver);

		}
		return stopSignalReceiver;
	}

	public static void main(String[] args) throws InterruptedException {
		StopSignalReceiver stopSignalHandler = new StopSignalReceiver();
		// 注册信号
		Signal sig = new Signal("TERM");
		Signal.handle(sig, stopSignalHandler);
		while (!StopSignalReceiver.isReceived()) {
			System.out.println("hello");
			Thread.sleep(1000);
		}
	}
}
